<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>  
  <?php include ("config.php"); ?>
  <script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=<?=GMAP_KEY?>"
            type="text/javascript">
  </script>
  <style type="text/css">
  body {
    margin: 0; 
    padding: 0;
    text-align: center; 
	background: #E5E5E5 url(images/pageBG.jpg) repeat-x;
	}
  </style>
  <?php	include ("utils.php");
	  	include(ROOT_DIR_CLASES.'/cCliente.php'); 
  		include(ROOT_DIR_CLASES.'/log.php');
  		include(ROOT_DIR_CLASES.'/posiMovil.php');
  		require_once 'JSON.php';
  	
  	if (!isset($_SESSION['cliente'])) {
  		log::errorJS('Sesion expirada...');
  		exit();
  	}
	$objetivo = $_SESSION['objetivo'];
	
	/************************************************************************
	CONFIGURACION INICIAL
	*************************************************************************/
		include("config.php");
		require_once(ROOT_DIR_CLASES.'/cResultado.php');
		require_once(ROOT_DIR_CLASES.'/cConfiguracion.php'); 
  		require_once(ROOT_DIR_CLASES.'/MiConfig.php');
		$cta = $_SESSION['uniqueID'];
		$esFlota = '0';
		if ($objetivo == 3) 
			$esFlota = '1';
	
		$configRegistrada = cConfiguracion::getConfig($cta, $esFlota);
		$miConfig = new MiConfig();
		if ($configRegistrada->cantidad()>0){ //tiene configuracion inicial
			$miConfig->id = $configRegistrada->campo('ORDER_ID',0);
			//Historico
			$miConfig->HIScolor = $configRegistrada->campo('HIS_color',0);
			$miConfig->HISthickness = $configRegistrada->campo('HIS_thickness',0);
			$miConfig->HISversentido = $configRegistrada->campo('HIS_sentido',0);
			$miConfig->HISvelexceso = $configRegistrada->campo('HIS_exceso',0);
			$miConfig->HISfiltrocero = $configRegistrada->campo('HIS_filtrocero',0);
			//Puntos
			$puntosVisibles = cConfiguracion::getPuntosVisibles($cta, $esFlota);
			for($i = 0;  $i < $puntosVisibles->cantidad(); $i++ ) {
				$miConfig->putPuntoId($puntosVisibles->campo('PUNTO_ID',$i));
				}
			//Zonas
			$zonasVisibles = cConfiguracion::getZonasVisibles($cta, $esFlota);
			for($i = 0;  $i < $zonasVisibles->cantidad(); $i++ ) {
				$miConfig->putZonaId($zonasVisibles->campo('ZONA_ID',$i));
				}
			}
		else{ //no tiene configuracion inicial .:. levanto la configuracion por defecto...
			$miConfig->id = '';
			//Historico
			$miConfig->HIScolor = HIS_COLOR;
			$miConfig->HISthickness = HIS_THICKNESS;
			$miConfig->HISversentido = HIS_VERSENTIDO;
			$miConfig->HISvelexceso = HIS_VELEXCESO;
			$miConfig->HISfiltrocero = HIS_FILTROCERO;		
			}
	/****************************************************************************/
  ?>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <link href="<?php echo ESTILO?>/gmap.css" rel="stylesheet" type="text/css">
    <link href="<?php echo ESTILO?>/minimenu.css" rel="stylesheet" type="text/css">
    <link href="<?php echo ESTILO?>/gmapsidebars.css" rel="stylesheet" type="text/css">
    
    <script src="js/gmap.js" type="text/javascript"></script>
	<script src="js/minimenu.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/jscolor/jscolor.js"></script>
    <script src="js/accordionMenu/SpryAccordion.js" type="text/javascript"></script>
	<link href="js/accordionMenu/SpryAccordion.css" rel="stylesheet" type="text/css" />
    <title>Google Maps</title>
    <script language="javascript" src="js/browserdetect.js"></script>
    <script language="javascript" src="js/json.js"></script>
    <script src="js/elabel.js" type="text/javascript"></script>
    <script src="js/mapiconmaker.js" type="text/javascript"></script>
    <script src="js/validator.js" type="text/javascript"></script>
    <script src="js/GMapSidebars/GMapSidebars.js" type="text/javascript"></script>
    <script src="js/GMapSidebars/sidebarTools.js" type="text/javascript"></script>
      
	<script src="js/PolylineEncoder.js" type="text/javascript"></script>
    <script src="js/BdccArrowedPolyline.js" type="text/javascript"></script>
    
    <!-- Calendar Settings -->
	<link href="<?php echo CALENDAR?>/skins/winter/theme.css" rel="stylesheet" type="text/css"/>
	<script type="text/javascript" src="<?php echo CALENDAR?>/calendar.js"></script>
	<script type="text/javascript" src="<?php echo CALENDAR?>/lang/calendar_es.js"></script>
	<script type="text/javascript" src="<?php echo CALENDAR?>/calendar_setup.js"></script>
	<!-- Color Picker -->
	<script language=JavaScript src="js/picker.js"></script>
    <!-- DHTML Window -->
    <link rel="stylesheet" href="js/dhtmlwindow/windowfiles/dhtmlwindow.css" type="text/css" /> 
    <link rel="stylesheet" href="js/dhtmlwindow/modalfiles/modal.css" type="text/css" /> 
	<script type="text/javascript" src="js/dhtmlwindow/windowfiles/dhtmlwindow.js">	
	/***********************************************
	* DHTML Window Widget- © Dynamic Drive (www.dynamicdrive.com)
	* This notice must stay intact for legal use.
	* Visit http://www.dynamicdrive.com/ for full source code
	***********************************************/
	</script>
    <script type="text/javascript" src="js/dhtmlwindow/modalfiles/modal.js"></script>
    <!-- POPUP MENU -->
    <script src="js/popupmenu.js" type="text/javascript"></script>
    <!-- HASHTABLE -->
    <script src="js/jshashtable.js" type="text/javascript"></script>
    <!-- ADD TOOLS -->
    <script src="js/GMapTools/toolMedicion.js" type="text/javascript"></script>
    <!-- DTREE MENU -->
    <link rel="stylesheet" href="js/dtree/dtree.css" type="text/css" />
    <script src="js/dtree/dtree.js" type="text/javascript"></script>
    <!-- SPECIAL TOOLTIPS -->
    <script type="text/javascript" src="js/wzTooltip/wz_tooltip.js"></script>
    <!-- ODOMETER -->
    <script type="text/javascript" src="js/odometer/odometer.js"> </script> 

      
    <?php  include('GMapSidebars/monitorGMap.php'); ?>
    <script type="text/javascript">
    var map;
	var mapControls = Array();
	var mapEventsHandlers = new Hashtable(); //Handlers de los eventos del mapa
	var mapEventsFunctions = new Hashtable(); //funciones de los Handlers de los eventos del mapa
	var mapActiveCursor = 'default';
    var AccordionMenu;
	var PopUpMenuMap;
    var READY_STATE_UNINITIALIZED 	= 0;
	var READY_STATE_LOADING 		= 1;
	var READY_STATE_LOADED 			= 2;
	var READY_STATE_INTERACTIVE 	= 3;
	var READY_STATE_COMPLETE 		= 4;
	var NOT_BUSY_IMAGE = "/images/loader_inactive.gif";
	var BUSY_IMAGE = "/images/loader_pulse.gif";
	
	var properties = null;
	var cuentaSelectSegui = <?="'".$_REQUEST['cuentaSelectSegui']."'"?>;
	var cuentaSelectSelection = '-1';
	
	/*Convertir constantes PHP a JS*/
	var GEO_PROVINCIA = <?="'".GEO_PROVINCIA."'"?>;
	var GEO_CIUDAD = <?="'".GEO_CIUDAD."'"?>;
	var GEO_PAIS = <?="'".GEO_PAIS."'"?>;
	var MOVIL_ID = <?= $_REQUEST['cuenta']; ?>;
	var OBJETIVO = parseInt(<?= $_SESSION['objetivo'] ?>);
	var UNIQUE_ID = <?= $_SESSION['uniqueID']; ?>; 
	var CUENTA_SELECCIONADA = <?= $_REQUEST['v']; ?>;
	var COLOR_DEFAULT_RECORRIDO_INI = <?= "'".COLOR_DEFAULT_RECORRIDO_INI."'" ?>;	
	var COLOR_DEFAULT_RECORRIDO_FIN = <?= "'".COLOR_DEFAULT_RECORRIDO_FIN."'" ?>;
	
	var COLOR_DEFAULT_ZONA_GMAP = '<?= $miConfig->HIScolor; ?>';
	var PUNTOSVISIBLES_string = '<?= join(",", $miConfig->PUNTOSVISIBLESid); ?>';
	var ZONASVISIBLES_string = '<?= join(",", $miConfig->ZONASVISIBLESid); ?>';
	
	/*FLAGS*/
	var autoRefreshFlag = 0;
	var monitorActivoFlag = false;
	
    //FUNCIONES DE CENTRADO EN EL MAPA	
	function centrar(latitud, longitud) {
		map.panTo(new GLatLng(latitud, longitud));
	}
	
	function centrarEnPoly(poly) { //centra el mapa en un Polygon o una Polyline y ajusta niveles de zoom para que se vea todo.
		if(poly != null) {
  			bounds = poly.getBounds(); //retorna los limites de la poly
 			map.setCenter(bounds.getCenter());
 			map.setZoom(map.getBoundsZoomLevel(bounds));
			}
	}
	
	function centrarEnPuntos(puntos) { //dado una lista de puntos (GLatLng) centra el mapa y ajusta niveles de zoom para que se vean todos.
		if((puntos!=null)&&(puntos.length > 1)) {
  			bounds = new GLatLngBounds(puntos[0],puntos[1]); //creamos un objeto bounds
			for (i=2; i<puntos.length;i++) //ampliamos el rectangulo 'bounds' para que quepan todos los puntos
				bounds.extend(puntos[i]);
 			map.setCenter(bounds.getCenter());
 			map.setZoom(map.getBoundsZoomLevel(bounds));
			}
	}

/****************************(REFRESH)********************************/

	function OnReadyStateChange() {
    	var ready = reqHandler.readyState;
		if (ready == READY_STATE_COMPLETE) {
			//si los vehiculos aun no estan cargados en su hash reintento cargarlos...
			if (misVehiculosHash.isEmpty()){
				CargarMisVehiculos();
			}
			
			//refresh POSICIONES DE VEHICULOS
			results = reqHandler.responseText.parseJSON();
			if (results.length != 'undefined') { 
				var resultsLarge = results.length;
				for (var i = 0; i < resultsLarge-1; i++) {
					if (misVehiculosHash.containsKey(results[i].id)){
						misVehiculosHash.get(results[i].id).POSIMOVIL = results[i];
						putIconCar(results[i].id);
						}
				}
				if(results[resultsLarge-1]>0){ //EXISTEN MENSAJES EN CHAT ALIVE!
						document.getElementById('alertChatIncomming').title='Usted tiene '+results[resultsLarge-1]+' mensajes sin leer en Chat Live!';
						document.getElementById('alertChatIncomming').style.display = "block";					
				   }
				else document.getElementById('alertChatIncomming').style.display = "none";					
			}

			//refresh panel SEGUIMIENTO
			refreshMovilSeguimiento(); 
			//refresh panel SELECCION
			refreshMovilSelection();
			//refresh eventos en MONITOR
			CargarEventosMonitor(); 
			
			$j("#iconoMapa").removeClass().addClass("icono_mapa");
			autoRefreshFlag = 0;
			reqHandler = null;
		}
    }
	
	function RefreshForm() {
    	autoRefreshFlag = 1;
    	$j("#iconoMapa").removeClass().addClass("icono_mapa_activo");
    	if (msie) 
            reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
        else
            reqHandler = new XMLHttpRequest();

        reqHandler.onreadystatechange = OnReadyStateChange;    
        reqHandler.open("POST", "querycontroller.php", true);
        reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        var aux = "COMMAND=REFRESH&" + reqParams +'&UNIQUEID='+UNIQUE_ID+'&OBJETIVO='+OBJETIVO;
		reqHandler.send(aux);
    }
	
	function AutoRefreshForm() {
    	if (autoRefreshFlag == 0) {
    		RefreshForm();
    	}
    }
	
	var menuVisible = true;
	function collapseMenuBar(){
		mapWidth = document.getElementById('map_canvas').offsetWidth;		
		if (menuVisible){
			accordionWidth = document.getElementById('AccordionMenu').offsetWidth;
			document.getElementById('sliceMenuBarIcon').className = 'sliceMenuBarIconIn';
			menuVisible = false;
			document.getElementById('gMapMenuBar').style.width='10px';
			document.getElementById('AccordionMenu').style.display = "none";
			document.getElementById('gMapMainContent').style.marginRight ='18px';			
			}
		else{
			document.getElementById('sliceMenuBarIcon').className = 'sliceMenuBarIconOut';
			menuVisible = true;
			document.getElementById('gMapMenuBar').style.width='325px';
			document.getElementById('AccordionMenu').style.display = "block";
			document.getElementById('gMapMainContent').style.marginRight = '333px';
			}
	}
	
    </script>
     
  </head>
  <body onload="initialize()" onunload="GUnload()" onresize="resizear()">
  
  <div id="gMapContainer">

    <div id="gMapHeader">
    	<img src="images/gmapsLogo.gif" align="left">   	
        <div style="height:60px; width:300px; background:url(imagenes/logomaps.jpg) center no-repeat; float:right; text-align:right;">
        	<div style="width:100%; height:20px;"><img id="busyImg" src="images/loader_pulse.gif" style="vertical-align:bottom" align="right"></div>
            <div style="width:100%"><img id="alertChatIncomming" src="images/chat/alertChatIncomming.gif" style="vertical-align:bottom; display:none;" align="right"></div>
        </div>
    </div>
    
    <div id="gMapMenuBar">
    	
    	<script language=JavaScript src="js/GMapPanels/vehiculos.js"></script>
        <script language=JavaScript src="js/GMapPanels/seguimiento.js"></script>
        <script language=JavaScript src="js/GMapPanels/seleccion.js"></script>
        <script language=JavaScript src="js/GMapPanels/historico.js"></script>
    	<script language=JavaScript src="js/GMapPanels/mispuntos.js"></script>
        <script language=JavaScript src="js/GMapPanels/miszonas.js"></script>
        <script language=JavaScript src="js/GMapPanels/reglas.js"></script>
      
        <!-- DIV generico para crear el contenido de las ventanas DHTMLWindow -->
        <div id="genericDHTMLWindowDiv" style="display:none; text-align:left;" align="left"></div>
        <table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
        <tr>
        <td width="10" valign="middle" align="center" style="background:#E3E3E3 url(images/collapsableBarBG.gif) repeat-y; cursor:pointer;" bgcolor="#FFC0C0" onclick="collapseMenuBar();" >
        	<div id="sliceMenuBarIcon" class="sliceMenuBarIconOut"></div>
        </td> 
        <td valign="top">   
 	    <div id="AccordionMenu" class="Accordion" tabindex="0">
	  	<?php 
	  		include('GMapPanels/vehiculos.php');
			include('GMapPanels/seguimiento.php');
			include('GMapPanels/seleccion.php');
			include('GMapPanels/historico.php');
			include('GMapPanels/referencias.php');
			include('GMapPanels/mispuntos.php');
			include('GMapPanels/miszonas.php');
			include('GMapPanels/reglas.php');
		?>	
		</div>
        </td>
        </tr>
        </table>
    </div>
    
    <div id="gMapMainContent">
    	<div id="map_canvas" style="width: 100% !important; width: 99%; height:500px; border:2px outset gray;"></div>
    </div>
 
  </div>

<script>

	function initMapEvents() {
		var eventosMap = mapEventsHandlers.values();
		for (var i=0; i<eventosMap.length; i++)
			GEvent.removeListener(eventosMap[i]);
		mapEventsHandlers.clear();
		mapEventsFunctions.clear();
		var mapMouseOver = function(){
		    map.showControls();
		 };
		mapEventsFunctions.put("mouseover", mapMouseOver); 
		mapEventsHandlers.put("mouseover",GEvent.addListener(map, "mouseover", mapMouseOver));
		var mapMouseOut = function(){
		   // map.hideControls();
		 };
		mapEventsFunctions.put("mouseout", mapMouseOut);
		mapEventsHandlers.put("mouseout",GEvent.addListener(map, "mouseout", mapMouseOut));
		mapActiveCursor = 'default';
		map.getDragObject().setDraggableCursor('default');
	}

	var sideMonitor;
	function initialize() {
	  $j("#iconoMapa").removeClass().addClass("icono_mapa");
	  AccordionMenu = new Spry.Widget.Accordion("AccordionMenu");
      if (GBrowserIsCompatible()) {
      	map = new GMap2(document.getElementById("map_canvas"), {mapTypes:[<?=GMAP_TYPES_MAPS?>]}); 
		mapControls.push(new GLargeMapControl());
		//mapControls.push(new GMapTypeControl());
		mapControls.push(new GMenuMapTypeControl());
		
		mapControls.push(new GOverviewMapControl());
		for (var i=0; i<mapControls.length; i++)
			map.addControl(mapControls[i]);
        map.setCenter(new GLatLng(<?=$_REQUEST['x']?>,<?=$_REQUEST['y']?>), <?=GMAP_INITIAL_ZOOM?>);
        //map.hideControls();
  		initMapEvents();
		
		//creo e inicio SideBar MONITOR
		sideMonitor = new sideBlockControl({sideBlockWidth:"100%", openText:"Monitor", titleBar:"Monitor"});
		map.addControl(sideMonitor);
		sideMonitor.hide();
		sideMonitor.container.appendChild(document.getElementById('monitor_content'));
		showDiv('monitor_content');
		
		//creo e inicio el SideBar GMAP TOOLS
		var sideBarTools = new sidebarTools();
		map.addControl(sideBarTools);
				
		CargarMisVehiculos();
		CargarMisGrupos();//carga los grupos de "MisPuntos"
		CargarMisZonas();
		CargarReglas();
		
        RefreshForm();
		setInterval("AutoRefreshForm();", eval(<?= GMAP_MAPA_REFRESH_AVL ?>) * 1000);
      }
    }
	
	function resizear() {
	  var theHeight = 0;
	  if (window.innerHeight) {
		theHeight=window.innerHeight;
		}
	  else if (document.documentElement && document.documentElement.clientHeight) {
				theHeight=document.documentElement.clientHeight;
			}
		   else if (document.body) {
				theHeight=document.body.clientHeight;
		    	}
	if (theHeight > 590){			  
		mapHeight = theHeight - 90;
		}
	else {
		mapHeight = 500;
		}
	for (var i=0; i<mapControls.length; i++)
		map.removeControl(mapControls[i]);
	document.getElementById('map_canvas').style.height = mapHeight + "px";
	document.getElementById('gMapMenuBar').style.height = mapHeight + "px";
	for (var i=0; i<mapControls.length; i++)
		map.addControl(mapControls[i]);
    }
	
	function cleanAllStates(){
		cleanEstadoNuevoPunto();
		cleanEstadoModificarPunto();
		cleanEstadoBuscarPunto();
		cleanEstadoNuevoGrupo();
		cleanEstadoNuevaZona();
		cleanEstadoNuevaRegla();
		cleanEstadoAplicarRegla();
		cleanEstadoCentroDeComandos();
	}
	
</script>

</body>
</html>
